/*
 * Util
 *
 * SJSU CS 149 Spring 2009 Project
 *
 * Copyright 2009 Timmy Yee
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Collection;
import java.util.Iterator;

/**
 * The Util class is a utility class that contains miscellaneous functions.
 *
 * @author Miaoer Yu
 */
public final class Util
{
    /**
     * A private constructor to prevent instantiating this static class.
     */
    private Util() {}

    /**
     * Joins a collection of strings together with the delimiter in between.
     *
     * @param s         The collection of strings.
     * @param delimiter Something to put in between the strings.
     * @return          The combined string.
     */
    public static String join(Collection<String> s, String delimiter)
    {
        if (s.isEmpty())
            return "";

        Iterator<String> iter = s.iterator();
        StringBuffer buffer = new StringBuffer(iter.next());

        while (iter.hasNext())
            buffer.append(delimiter).append(iter.next());

        return buffer.toString();
    }

    /**
     * Checks if two double values are equal.
     *
     * @param a The first double value.
     * @param b The second double value.
     * @return  True if the double values are equal, false otherwise.
     */
    public static boolean areDoublesEqual(double a, double b)
    {
        return Math.abs(a - b) < 0.001;
    }

    /**
     * Checks if the number is a whole number (in other words, an integer).
     *
     * @param n The given number.
     * @return  True if the number is whole, false otherwise.
     */
    public static boolean isWholeNumber(double n)
    {
        return Util.areDoublesEqual(n - Math.round(n), 0);
    }

    /**
     * Rounds a number to the nearest tenth.
     *
     * @param number    A number that is a double floating-point value.
     * @return          The number rounded to the nearest tenth.
     */
    public static double nearestTenth(double number)
    {
        return Double.parseDouble(String.format("%.1f", number));
    }
}

